package com.framework;

import lombok.Data;

import java.util.List;
import java.util.Map;

// 工作流引擎
@Data
class WorkflowEngine {
    private final ComponentRegistry registry;

    public WorkflowEngine(ComponentRegistry registry) {
        this.registry = registry;
    }

    public ComponentOutput<?> execute(BusinessWorkflow workflow, ComponentContext<?> context) {
        Object currentData = context.getRequestData();

        for (BusinessWorkflow.WorkflowStep step : workflow.getSteps()) {
            Component<Object, Object> component = (Component<Object, Object>) registry.getComponent(step.getComponent());

            // 准备输入数据
            ComponentContext<Object> stepContext = new ComponentContext<>();
            stepContext.setRequestData(currentData);
            stepContext.getContextData().putAll(context.getContextData());

            // 执行组件
            ComponentOutput<Object> output = component.execute(stepContext);

            // 处理条件
            if (step.getConditions() != null && !step.getConditions().isEmpty()) {
                if (!evaluateConditions(output, step.getConditions())) {
                    // 条件不满足，停止执行
                    return output;
                }
            }

            // 处理输出映射
            if (output.isSuccess() && step.getOutputMappings() != null) {
                currentData = applyOutputMappings(output.getData(), step.getOutputMappings());
            }
        }

        return ComponentOutput.success(currentData);
    }

    private boolean evaluateConditions(ComponentOutput<?> output, List<String> conditions) {
        // 实际实现应使用表达式引擎
        return conditions.stream().allMatch(cond -> cond.equals("SUCCESS") ? output.isSuccess() : true);
    }

    private Object applyOutputMappings(Object data, Map<String, String> mappings) {
        // 实际实现应使用映射引擎
        return data;
    }
}

